﻿#批量命名图片
import os,time,re

ROOT_PATH = os.path.abspath('..')
print("是否开始重名",ROOT_PATH ,"该目录下的所有图片文件\n")

answer=input("是y/否n:\n")
if answer!="y":
	exit()

print("-------------开始重命名-------------")
st = time.time()

def joinPath(name):
	name = os.path.join(ROOT_PATH,name)
	return name

#获取后缀
def getFix(url):
	fix = os.path.splitext(os.path.join(ROOT_PATH,url))[1]
	return fix
#获取文件名
def getName(url):
	fname = os.path.splitext(os.path.join(ROOT_PATH,url))[0]
	return fname
	
def renameImg(old,new):
	os.rename(old,new)

#获取新的文件名字	
def getNewName(i,fix):
	src = "00000"
	src = src[0:(len(src)-len(str(i)))]+str(i);
	src=joinPath(src+fix) 
	return src

regObj = re.compile(r'\d+$')
def isPureNum(fname):
	ret = regObj.match(fname)	
	return ret and len(fname)==5
	
allImages=[x for x in os.listdir(ROOT_PATH) if os.path.isfile(os.path.join(ROOT_PATH,x)) and (os.path.splitext(os.path.join(ROOT_PATH,x))[1]=='.png' or os.path.splitext(os.path.join(ROOT_PATH,x))[1]=='.jpg') ]

ownNums = [];
strFiles = [];
for fname in allImages:
	arr = re.split(r'\.',fname)
	if isPureNum(arr[0]):		
		ownNums.append(int(arr[0]))
	else:
		strFiles.append(fname)

ownNums.sort()
		
def getUnUseNum(i):	
	while i in ownNums:
		i = i+1	
	return i
#批量重命名
def batRename():
	index = 0;
	logs="";
	for fname in strFiles:	
		index = getUnUseNum(index)
		oldn = joinPath(fname)
		newn = getNewName(index,getFix(fname))
		renameImg(oldn,newn)
		index = index+1
		logs = logs + "文件:"+oldn+";被重命名为:"+newn+"\r"
	et = time.time()
	ct = round(et - st,2);
	print("共重命名%s个文件,耗时"%len(strFiles),ct,"毫秒")
	if logs!="":		
		cururl = os.path.join(os.path.abspath(os.curdir),"logs.txt")
		if os.path.isfile(cururl):
			os.remove(cururl)			
		with open(cururl,'w') as f:
			f.write(logs)

batRename();

